﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Utility;
using System.ComponentModel;
using Sector7.Medical.Biz;
using Sector7.Medical.INFM.Windows;
using Sector7.Framework.Enums;
using Sector7.Medical.Consts;
using Sector7.Medical.Utility;
using Sector7.Medical.EntityType;
using Sector7.Medical.Controls;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// DrugSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class DrugSummaryControl : SummaryControlBase
    {
        #region Accessor
        private M7_Drug Drug
        {
            get { return m_entity as M7_Drug; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        /// <summary>
        /// 获取物理分类列表
        /// </summary>
        /// <returns></returns>
        public List<M7_DrugType> GetPhysicalTypeList()
        {
            return m_physicalTypeList;
        }
        #endregion

        #region Private functions
        protected override void SwitchDetailControlsStatus(CrudType crud)
        {
            switch (crud)
            {
                case CrudType.Read:
                    gpbName.IsEnabled = false;
                    gpbDetail.IsEnabled = false;
                    break;
                case CrudType.Create:
                    var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;

                    if (selectedTypeNode != null)
                    {
                        var selectedType = selectedTypeNode.Tag as M7_DrugType;
                        cbbNatureType.SelectedValue = selectedType.DrugTypeId;
                    }

                    gpbName.IsEnabled = true;
                    gpbDetail.IsEnabled = true;
                    break;
                case CrudType.Update:
                    gpbName.IsEnabled = true;
                    gpbDetail.IsEnabled = true;
                    break;
                default:
                    break;
            }

            base.SwitchDetailControlsStatus(crud);
        }

        private new void GetData()
        {
            m_physicalTypeList = Agent_INFS.GetDrugTypeTree();
            m_drugFormList = Agent_INFS.GetDrugFormList();
            m_specUnitList = Agent_INFS.GetUnitListByFlags(C_UnitFlags.SPEC_UNIT);
            m_usageUnitList = Agent_INFS.GetUnitListByFlags(C_UnitFlags.USAGE_UNIT);
            m_drugRegTypeList = Agent_INFS.GetDrugRegTypeList();
        }

        private TreeViewItem CreatePhysicalTypeNode(M7_DrugType physicalType)
        {
            var physicalTypeNode = new TreeViewItem();
            physicalTypeNode.Margin = new Thickness(0, 3, 0, 3);
            physicalTypeNode.Header = physicalType.DrugTypeName;
            physicalTypeNode.Tag = physicalType;
            physicalTypeNode.IsExpanded = true;
            physicalTypeNode.ContextMenu = CreatePhysicalTypeMenu();

            if (physicalType.Children != null)
            {
                foreach (var natureType in physicalType.Children)
                {
                    physicalTypeNode.Items.Add(CreateNatureTypeNode(natureType));
                }
            }

            return physicalTypeNode;
        }

        private TreeViewItem CreateNatureTypeNode(M7_DrugType natureType)
        {
            var natureTypeNode = new TreeViewItem();
            natureTypeNode.Margin = new Thickness(0, 3, 0, 3);
            natureTypeNode.Header = natureType.DrugTypeName + "[...]";
            natureTypeNode.Tag = natureType;
            natureTypeNode.IsExpanded = true;
            natureTypeNode.ContextMenu = CreateNatureTypeMenu();

            return natureTypeNode;
        }

        private ContextMenu CreatePhysicalTypeMenu()
        {
            var menu = new ContextMenu();

            var miCreate = new MenuItem();
            miCreate.Header = "添加二级分类";
            miCreate.Tag = CrudType.Create;
            miCreate.Click += new RoutedEventHandler(PhysicalTypeMenuItem_Click);
            var miModify = new MenuItem();
            miModify.Header = "修改";
            miModify.Tag = CrudType.Update;
            miModify.Click += new RoutedEventHandler(PhysicalTypeMenuItem_Click);
            var miDelete = new MenuItem();
            miDelete.Header = "删除";
            miDelete.Tag = CrudType.Delete;
            miDelete.Click += new RoutedEventHandler(PhysicalTypeMenuItem_Click);

            menu.Items.Add(miCreate);
            menu.Items.Add(miModify);
            menu.Items.Add(miDelete);

            return menu;
        }

        void PhysicalTypeMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            switch ((CrudType)menuItem.Tag)
            {
                case CrudType.Create:
                    AddNatureType();
                    break;
                case CrudType.Update:
                    ModifyPhysicalType();
                    break;
                case CrudType.Delete:
                    DeletePhysicalType();
                    break;
                default:
                    break;
            }
        }

        private ContextMenu CreateNatureTypeMenu()
        {
            var menu = new ContextMenu();

            var miModify = new MenuItem();
            miModify.Header = "修改";
            miModify.Tag = CrudType.Update;
            miModify.Click += new RoutedEventHandler(NatureTypeMenuItem_Click);
            var miDelete = new MenuItem();
            miDelete.Header = "删除";
            miDelete.Tag = CrudType.Delete;
            miDelete.Click += new RoutedEventHandler(NatureTypeMenuItem_Click);

            menu.Items.Add(miModify);
            menu.Items.Add(miDelete);

            return menu;
        }

        void NatureTypeMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            switch ((CrudType)menuItem.Tag)
            {
                case CrudType.Update:
                    ModifyNatureType();
                    break;
                case CrudType.Delete:
                    DeleteNatureType();
                    break;
                default:
                    break;
            }
        }

        private void LoadData()
        {
            trvMain.Items.Clear();            

            foreach (var physicalType in m_physicalTypeList)
            {
                trvMain.Items.Add(CreatePhysicalTypeNode(physicalType));

                if (physicalType.Children != null)
                {
                    if (m_natureTypeList == null)
                    {
                        m_natureTypeList = new List<M7_DrugType>();
                    }
                    m_natureTypeList.AddRange(physicalType.Children);
                }
            }

            ClientUtil.LoadItemsSource(cbbNatureType, m_natureTypeList);
            ClientUtil.LoadItemsSource(cbbDrugForm, m_drugFormList);
            ClientUtil.LoadItemsSource(cbbSpecUnit, m_specUnitList);
            ClientUtil.LoadItemsSource(cbbUsageUnit, m_usageUnitList);
            ClientUtil.LoadItemsSource(cbbDrugRegType, m_drugRegTypeList);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void LoadDrugList()
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            var selectedType = selectedTypeNode.Tag as M7_DrugType;
            selectedType.DrugList = m_currentDrugList;

            string header = selectedTypeNode.Header.ToString();
            selectedTypeNode.Header = header.Replace("...", m_currentDrugList.Count.ToString());
            ClientUtil.LoadItemsSource(dtgMain, m_currentDrugList);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void LoadDrug(M7_Drug selectedDrug)
        {
            if (selectedDrug != null)
            {
                txbDrugId.Text = selectedDrug.DrugId.ToString();
                cbbNatureType.SelectedValue = selectedDrug.NatureTypeId;
                txbDrugName.Text = selectedDrug.DrugName;
                txbSpellCode.Text = selectedDrug.SpellCode;
                txbProductName.Text = selectedDrug.ProductName;
                cbbDrugForm.SelectedValue = selectedDrug.DrugFormId;
                cbbUsageUnit.SelectedValue = selectedDrug.UsageUnitId;
                txbSpec.Text = selectedDrug.Spec.ToString();
                cbbSpecUnit.SelectedValue = selectedDrug.SpecUnitId;
                txbExeStandard.Text = selectedDrug.ExecutiveStandard;
                cbbDrugRegType.SelectedValue = selectedDrug.DrugRegTypeId;
                txbDrugRegNumber.Text = selectedDrug.DrugRegNumber;
                txbBarCode.Text = selectedDrug.BarCode;
            }
            else
            {
                txbDrugId.Text = null;
                cbbNatureType.SelectedValue = null;
                txbDrugName.Text = null;
                txbSpellCode.Text = null;
                txbProductName.Text = null;
                cbbDrugForm.SelectedValue = null;
                cbbUsageUnit.SelectedValue = null;
                txbSpec.Text = null;
                cbbSpecUnit.SelectedValue = null;
                txbExeStandard.Text = null;
                cbbDrugRegType.SelectedValue = null;
                txbDrugRegNumber.Text = null;
                txbBarCode.Text = null;
            }
        }

        private void AddModeControlBase_Loaded(object sender, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;
            Menvironments.MainControl = this;

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
            worker.RunWorkerAsync();
        }

        private void AddModeControlBase_AddSuccess(object sender, EventArgs e)
        {
            switch (m_crud)
            {
                case CrudType.Create:
                    foreach (TreeViewItem physicalTypeNode in trvMain.Items)
                    {
                        var physicalType = physicalTypeNode.Tag as M7_DrugType;
                        if (physicalType.DrugTypeId == Drug.PhysicalTypeId)
                        {
                            foreach (TreeViewItem natureTypeNode in physicalTypeNode.Items)
                            {
                                var natureType = natureTypeNode.Tag as M7_DrugType;
                                if (natureType.DrugTypeId == Drug.NatureTypeId)
                                {
                                    if (natureType.DrugList == null)
                                    {
                                        SelectTreeViewItem(natureTypeNode);
                                    }
                                    else
                                    {
                                        natureType.DrugList.Add(Drug);
                                        natureTypeNode.Header = string.Format("{0}[{1}]", natureType.DrugTypeName, natureType.DrugList.Count);
                                        natureTypeNode.IsSelected = true;

                                        ClientUtil.LoadItemsSource(dtgMain, natureType.DrugList);
                                    }

                                    goto UPDATE_COMPLETED_FOR_CREATING;
                                }
                            }
                        }
                    }
            UPDATE_COMPLETED_FOR_CREATING:
                    break;
                case CrudType.Update:
                    foreach (TreeViewItem physicalTypeNode in trvMain.Items)
                    {
                        var physicalType = physicalTypeNode.Tag as M7_DrugType;
                        if (physicalType.DrugTypeId == Drug.PhysicalTypeId)
                        {
                            foreach (TreeViewItem natureTypeNode in physicalTypeNode.Items)
                            {
                                var natureType = natureTypeNode.Tag as M7_DrugType;
                                if (natureType.DrugTypeId == Drug.NatureTypeId)
                                {
                                    natureType.DrugList.Find(delegate(M7_Drug drug)
                                    {
                                        if (drug.DrugId == Drug.DrugId)
                                        {
                                            drug = Drug;
                                            return true;
                                        }
                                        else
                                        {
                                            return false;
                                        }
                                    });

                                    natureTypeNode.IsSelected = true;

                                    ClientUtil.LoadSelectedItem(dtgMain, Drug);

                                    goto UPDATE_COMPLETED_FOR_UPDATING;
                                }
                            }
                        }
                    }
            UPDATE_COMPLETED_FOR_UPDATING:
                    break;
                default:
                    break;
            }

            m_crud = CrudType.Unknown;
        }

        void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        private void btnAddPhysicalType_Click(object sender, RoutedEventArgs e)
        {
            AddPhysicalType();
        }

        private void AddPhysicalType()
        {
            var addPhysicalTypeWindow = new AddPhysicalTypeWindow();
            addPhysicalTypeWindow.InitializeWindow(CrudType.Create);
            addPhysicalTypeWindow.AddSuccess += new EventHandler(AddPhysicalTypeWindow_AddSuccess);

            addPhysicalTypeWindow.ShowDialog();
        }

        private void ModifyPhysicalType()
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            if (selectedTypeNode != null)
            {
                var modifyPhysicalTypeWindow = new AddPhysicalTypeWindow();
                modifyPhysicalTypeWindow.PhysicalType = selectedTypeNode.Tag as M7_DrugType;
                modifyPhysicalTypeWindow.InitializeWindow(CrudType.Update);
                modifyPhysicalTypeWindow.AddSuccess += new EventHandler(AddPhysicalTypeWindow_AddSuccess);

                modifyPhysicalTypeWindow.ShowDialog();
            }
        }

        private void DeletePhysicalType()
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            if (selectedTypeNode != null)
            {
                MessageBoxResult result = Alert.ShowDialog(AlertType.Question, "删除该分类后，其下所有数据将丢失，是否继续？");
                if (result == MessageBoxResult.Yes)
                {
                    var selectedType = selectedTypeNode.Tag as M7_DrugType;
                    Agent_INFS.DeleteDrugType(selectedType.DrugTypeId);
                    trvMain.Items.Remove(selectedTypeNode);
                    m_physicalTypeList.Remove(selectedType);
                }
            }
        }

        void AddPhysicalTypeWindow_AddSuccess(object sender, EventArgs e)
        {
            var addPhysicalTypeWindow = sender as AddPhysicalTypeWindow;
            M7_DrugType newPhysicalType = addPhysicalTypeWindow.PhysicalType;

            switch (addPhysicalTypeWindow.Crud)
            {
                case CrudType.Create:
                    var newPhysicalTypeNode = CreatePhysicalTypeNode(newPhysicalType);
                    trvMain.Items.Add(newPhysicalTypeNode);                    
                    break;
                case CrudType.Update:
                    var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
                    if ((selectedTypeNode.Tag as M7_DrugType).DrugTypeId == newPhysicalType.DrugTypeId)
                    {
                        selectedTypeNode.Header = newPhysicalType.DrugTypeName;
                        selectedTypeNode.Tag = newPhysicalType;

                        ClientUtil.UpdateToItems<M7_DrugType>(m_physicalTypeList, C_ColumnName.DRUG_TYPE_ID, newPhysicalType);
                    }
                    break;
                default:
                    break;
            }
        }

        private void btnAddNatureType_Click(object sender, RoutedEventArgs e)
        {
            AddNatureType();
        }

        private void AddNatureType()
        {
            var addNatureTypeWindow = new AddNatureTypeWindow();            
            addNatureTypeWindow.InitializeWindow(CrudType.Create);
            addNatureTypeWindow.AddSuccess += new EventHandler(AddNatureTypeWindow_AddSuccess);

            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            if (selectedTypeNode != null)
            {
                addNatureTypeWindow.CurrentParentType = selectedTypeNode.Tag as M7_DrugType;
            }

            addNatureTypeWindow.ShowDialog();
        }

        private void ModifyNatureType()
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            if (selectedTypeNode != null)
            {
                var modifyNatureTypeWindow = new AddNatureTypeWindow();
                modifyNatureTypeWindow.NatureType = selectedTypeNode.Tag as M7_DrugType;
                modifyNatureTypeWindow.InitializeWindow(CrudType.Update);
                modifyNatureTypeWindow.AddSuccess += new EventHandler(AddNatureTypeWindow_AddSuccess);

                modifyNatureTypeWindow.ShowDialog();
            }
        }

        private void DeleteNatureType()
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            if (selectedTypeNode != null)
            {
                MessageBoxResult result = Alert.ShowDialog(AlertType.Question, "删除该分类后，其下所有数据将丢失，是否继续？");
                if (result == MessageBoxResult.Yes)
                {
                    var selectedType = selectedTypeNode.Tag as M7_DrugType;
                    Agent_INFS.DeleteDrugType(selectedType.DrugTypeId);
                    (selectedTypeNode.Parent as TreeViewItem).Items.Remove(selectedTypeNode);
                    m_natureTypeList.Remove(selectedType);
                }
            }
        }

        private void AddNatureTypeWindow_AddSuccess(object sender, EventArgs e)
        {
            var addNatureTypeWindow = sender as AddNatureTypeWindow;
            M7_DrugType newNatureType = addNatureTypeWindow.NatureType;

            switch (addNatureTypeWindow.Crud)
            {
                case CrudType.Create:
                    var newNatureTypeNode = CreateNatureTypeNode(newNatureType);
                    foreach (TreeViewItem parentTypeNode in trvMain.Items)
                    {
                        if ((parentTypeNode.Tag as M7_DrugType).DrugTypeId == newNatureType.ParentId)
                        {
                            parentTypeNode.Items.Add(newNatureTypeNode);
                            m_natureTypeList.Add(newNatureType);
                            ClientUtil.LoadItemsSource(cbbNatureType, m_natureTypeList);
                            break;
                        }
                    }
                    break;
                case CrudType.Update:
                    foreach (TreeViewItem parentTypeNode in trvMain.Items)
                    {
                        if ((parentTypeNode.Tag as M7_DrugType).DrugTypeId == newNatureType.ParentId)
                        {
                            foreach (TreeViewItem childTypeNode in parentTypeNode.Items)
                            {
                                if ((childTypeNode.Tag as M7_DrugType).DrugTypeId == newNatureType.DrugTypeId)
                                {
                                    childTypeNode.Header = newNatureType.DrugTypeName;
                                    childTypeNode.Tag = newNatureType;

                                    ClientUtil.UpdateToItems<M7_DrugType>(m_natureTypeList, C_ColumnName.DRUG_TYPE_ID, newNatureType);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void trvMain_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
            SelectTreeViewItem(selectedTypeNode);
        }

        private void SelectTreeViewItem(TreeViewItem selectedTypeNode)
        {            
            if (selectedTypeNode != null)
            {
                selectedTypeNode.IsSelected = true;
                var selectedType = selectedTypeNode.Tag as M7_DrugType;
                switch (selectedType.Flags)
                {
                    case C_DrugTypeFlags.PHYSICAL:
                        ClientUtil.UnLoadItemsSource(dtgMain);
                        break;
                    case C_DrugTypeFlags.NATURE:
                        if (selectedTypeNode.Header.ToString().Contains("..."))
                        {
                            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

                            var getDrugListWorker = BackgroundWorkerUtil.GetWorker(this);
                            getDrugListWorker.DoWork += new DoWorkEventHandler(GetDrugListWorker_DoWork);
                            getDrugListWorker.RunWorkerAsync(selectedType.DrugTypeId);
                        }
                        else
                        {
                            m_currentDrugList = selectedType.DrugList;
                            ClientUtil.LoadItemsSource(dtgMain, m_currentDrugList);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void GetDrugListWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int natureTypeId = Convert.ToInt32(e.Argument);
            m_currentDrugList = Agent_INFS.GetDrugListByNatureTypeId(natureTypeId);

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadDrugList));
        }

        private void dtgMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = dtgMain.SelectedItem as M7_Drug;

            LoadDrug(selectedItem);
        }

        private void CheckUnitIsExist()
        {
            if (cbbUsageUnit.SelectedItem == null && cbbUsageUnit.Text != null)
            {
                AppendNewUnitToComboBox(cbbUsageUnit, cbbUsageUnit.Text, C_UnitFlags.USAGE_UNIT);
            }
            if (cbbSpecUnit.SelectedItem == null && cbbSpecUnit.Text != null)
            {
                AppendNewUnitToComboBox(cbbSpecUnit, cbbSpecUnit.Text, C_UnitFlags.SPEC_UNIT);
            }
        }

        private void AppendNewUnitToComboBox(ComboBox comboBox, string unitName, int flags)
        {
            var unit = new M7_Unit();

            unit.UnitName = unitName;
            unit.Flags = flags;
            unit.UnitId = Agent_INFS.AddUnit(unit);

            List<M7_Unit> unitList = null;
            switch (flags)
            {
                case C_UnitFlags.USAGE_UNIT:
                    unitList = m_usageUnitList;
                    break;
                case C_UnitFlags.SPEC_UNIT:
                    unitList = m_specUnitList;
                    break;
                default:
                    break;
            }

            if (unitList != null)
            {
                unitList.Add(unit);
                ClientUtil.LoadItemsSource(comboBox, unitList);
                comboBox.SelectedItem = unit;
            }
        }

        protected override bool CheckData()
        {
            CheckUnitIsExist();

            m_errors.Clear();

            Drug.NatureType = cbbNatureType.SelectedItem as M7_DrugType;
            if (Drug.NatureType != null)
            {
                Drug.NatureTypeId = Drug.NatureType.DrugTypeId;
                Drug.PhysicalTypeId = Drug.NatureType.ParentId;
            }
            else
            {
                m_errors.Add("药品分类", "不能为空！");
            }
            Drug.DrugName = txbDrugName.Text;
            if (string.IsNullOrWhiteSpace(Drug.DrugName))
            {
                m_errors.Add("通用名称", "不能为空！");
            }
            else
            {
                if (Agent_INFS.GetDrugListByKeywords(Drug.DrugName).Count > 0)
                {
                    m_errors.Add("通用名称", "该药品已经添加！");
                }
            }
            Drug.SpellCode = txbSpellCode.Text;
            if (string.IsNullOrWhiteSpace(Drug.SpellCode))
            {
                m_errors.Add("拼音码", "不能为空！");
            }
            Drug.ProductName = txbProductName.Text;
            if (string.IsNullOrWhiteSpace(Drug.ProductName))
            {
                m_errors.Add("商品名称", "不能为空！");
            }
            else
            {
                if (Agent_INFS.CountByDrugName(Drug.ProductName) > 0)
                {
                    m_errors.Add("商品名称", "该药品已经添加！");
                }
            }
            Drug.DrugForm = cbbDrugForm.SelectedItem as M7_DrugForm;
            if (Drug.DrugForm != null)
            {
                Drug.DrugFormId = Drug.DrugForm.Value;
            }
            else
            {
                m_errors.Add("剂型", "不能为空！");
            }
            Drug.UsageUnit = cbbUsageUnit.SelectedItem as M7_Unit;
            if (Drug.UsageUnit != null)
            {
                Drug.UsageUnitId = Drug.UsageUnit.UnitId;
            }
            else
            {
                m_errors.Add("使用单位", "不能为空！");
            }
            if (string.IsNullOrWhiteSpace(txbSpec.Text))
            {
                m_errors.Add("规格", "不能为空！");
            }
            else
            {
                Drug.Spec = Convert.ToDecimal(txbSpec.Text);
            }
            Drug.SpecUnit = cbbSpecUnit.SelectedItem as M7_Unit;
            if (Drug.SpecUnit != null)
            {
                Drug.SpecUnitId = Drug.SpecUnit.UnitId;
            }
            else
            {
                m_errors.Add("规格单位", "不能为空！");
            }
            Drug.DrugRegType = cbbDrugRegType.SelectedItem as M7_DrugRegType;
            if (Drug.DrugRegType != null)
            {
                Drug.DrugRegTypeId = Drug.DrugRegType.Value;
            }
            else
            {
                m_errors.Add("医药产品注册类型", "不能为空！");
            }
            Drug.DrugRegNumber = txbDrugRegNumber.Text;
            if (string.IsNullOrWhiteSpace(Drug.DrugRegNumber))
            {
                m_errors.Add("医药产品注册证号", "不能为空！");
            }

            return base.CheckData();
        }

        protected override void AddData()
        {
            Drug.ExecutiveStandard = txbExeStandard.Text;
            Drug.BarCode = txbBarCode.Text;

            switch (m_crud)
            {
                case CrudType.Create:
                    string natureTypeId = Drug.NatureTypeId.ToString();
                    int seed = Agent_SYSS.GetBinarySeed(C_M7_TableName.DRUG, natureTypeId);
                    Drug.DrugId = Convert.ToInt64(PrimaryKeyUtil.GetPrimaryKey(C_M7_TableName.DRUG, natureTypeId, seed));
                    Agent_INFS.AddDrug(Drug);
                    break;
                case CrudType.Update:
                    bool isChanged = false;
                    var delta = GetDelta("DrugId", ref isChanged);
                    if (isChanged)
                    {
                        Agent_INFS.UpdateDrug(delta);
                    }
                    break;
                default:
                    break;
            }

            base.AddData();
        }

        protected override void InitializeForCreating()
        {
            m_crud = CrudType.Create;
            Drug = new M7_Drug();
            LoadDrug(null);

            base.InitializeForCreating();
        }

        protected override void InitializeForUpdating()
        {
            base.InitializeForUpdating();
        }

        private void btnSpellCode_Click(object sender, RoutedEventArgs e)
        {
            txbSpellCode.Text = CharacterUtil.GetSpellCodeString(txbDrugName.Text);
        }

        private void searchBox_KeywordsChanging(object sender, KeyEventArgs e)
        {
            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new DoWorkEventHandler(FilterWorker_DoWork);
            worker.RunWorkerAsync(searchBox.Keywords);
        }

        void FilterWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            m_tempDrugList = Agent_INFS.GetDrugListByKeywords(e.Argument.ToString());
            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadFilterDrugList));
        }

        private void LoadFilterDrugList()
        {
            ClientUtil.LoadItemsSource(dtgMain, m_tempDrugList);

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void searchBox_KeywordsReset(object sender, EventArgs e)
        {
            ClientUtil.LoadItemsSource(dtgMain, m_currentDrugList);
        }

        protected override void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            InitializeControl(CrudType.Create);

            base.btnAdd_Click(sender, e);
        }

        protected override void btnModify_Click(object sender, RoutedEventArgs e)
        {
            var selectedDrug = dtgMain.SelectedItem as M7_Drug;
            if (selectedDrug != null)
            {
                Drug = selectedDrug;
                InitializeControl(CrudType.Update);
            }

            base.btnModify_Click(sender, e);
        }

        protected override void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var selectedDrug = dtgMain.SelectedItem as M7_Drug;
            if (selectedDrug != null)
            {
                MessageBoxResult result = Alert.ShowDialog(AlertType.Question, "删除该药品信息后数据不可恢复，是否确认删除？");
                if (result == MessageBoxResult.Yes)
                {
                    Agent_INFS.DeleteDrug(selectedDrug.DrugId);
                    m_currentDrugList.Remove(selectedDrug);
                    dtgMain.Items.Refresh();

                    var selectedTypeNode = trvMain.SelectedItem as TreeViewItem;
                    if (selectedTypeNode != null)
                    {
                        var selectedType = selectedTypeNode.Tag as M7_DrugType;
                        selectedType.DrugList = m_currentDrugList;
                        selectedTypeNode.Header = string.Format("{0}[{1}]", selectedType.DrugTypeName, selectedType.DrugList.Count);
                    }
                }
            }

            base.btnDelete_Click(sender, e);
        }

        protected override void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (CheckData())
            {
                AddData();

                base.btnOk_Click(sender, e);
            }
            else
            {
                ShowErrors();
            }
        }

        protected override void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;
            LoadDrug(dtgMain.SelectedItem as M7_Drug);

            base.btnCancel_Click(sender, e);
        }
        #endregion

        #region Structure
        public DrugSummaryControl()
        {
            InitializeComponent();

            m_btnAdd = btnAdd;
            m_btnModify = btnModify;
            m_btnDelete = btnDelete;
            m_btnOk = btnOk;
            m_btnCancel = btnCancel;
        }
        #endregion

        #region Inner members
        private List<M7_DrugType> m_physicalTypeList = null;
        private List<M7_DrugType> m_natureTypeList = null;
        private List<M7_DrugForm> m_drugFormList = null;
        private List<M7_DrugRegType> m_drugRegTypeList = null;
        private List<M7_Unit> m_specUnitList = null;
        private List<M7_Unit> m_usageUnitList = null;
        private List<M7_Drug> m_currentDrugList = null;
        private List<M7_Drug> m_tempDrugList = null;
        #endregion
    }
}
